package com.zhuiYun.project.api.lott;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

public class ImageCompressor {

    public static void main(String[] args) throws IOException {
        String sourceImagePath = "D:\\ruoyi\\2024\\08\\03"; // 输入图片路径
        String compressedImagePath = "D:\\ruoyi\\uploadPath1\\2024\\08\\03\\"; // 输出压缩后图片路径
        File file = new File(sourceImagePath);
        File[] files = file.listFiles();
        int targetSizeKB = 200; // 目标压缩后文件大小，单位 KB
        for (File file1 : files) {
           // System.out.println(file1.getAbsoluteFile());
           // System.out.println(file1.getName());
            System.out.println(  file1.getPath());
            try{
                compressImageToKB(file1.getPath(), compressedImagePath+file1.getName(), targetSizeKB);
            }catch (Exception e){
                e.printStackTrace();
            }

        }


        //compressImage(sourceImagePath, compressedImagePath, targetSizeKB);
    }
    public static void compressImageToKB(String sourceImagePath, String outputImagePath, float imageSizeKB) throws IOException {
        File inputFile = new File(sourceImagePath);
        Thumbnails.of(inputFile)
                .scale(1f)
                .outputQuality(imageSizeKB / 1024)
                .toFile(outputImagePath);
    }
    public static void compressImage(String sourceImagePath, String compressedImagePath, int targetSizeKB) throws IOException {
        File inputFile = new File(sourceImagePath);
        BufferedImage inputImage = ImageIO.read(inputFile);

        // 设置初始压缩质量
        float compressQuality = 0.9f; // 初始压缩质量，可以根据需要调整

        // 创建一个 ByteArrayOutputStream 以便计算压缩后文件大小
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // 循环压缩直到满足大小限制
        do {
            // 压缩图片到 ByteArrayOutputStream
            compress(inputImage, baos, compressQuality);

            // 检查压缩后的大小
            int fileSizeKB = baos.size() / 1024;

            // 如果超过目标大小，则降低压缩质量
            if (fileSizeKB > targetSizeKB) {
                compressQuality -= 0.02f; // 降低压缩质量，可以根据需要微调步长
                baos.reset(); // 重置 ByteArrayOutputStream
            }
            System.out.println(baos.size());

        } while (baos.size() > targetSizeKB * 1024);

        // 将压缩后的图片写入文件
        File compressedImageFile = new File(compressedImagePath);
        ImageIO.write(inputImage, "jpg", compressedImageFile);

        System.out.println("压缩完成，目标文件大小约为 " + (compressedImageFile.length() / 1024) + " KB");
    }

    public static void compress(BufferedImage image, ByteArrayOutputStream baos, float compressQuality) throws IOException {
        ImageIO.write(image, "jpg", baos);
    }
}